package com.sczmgk.hotline_pzh.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.WebViewBaseActivity;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.db.impl.InformationTitleDaoImpl;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.IndicatorInfos;
import com.sczmgk.hotline_pzh.entity.InformationBean;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.jpush.MainHomeDataObserver;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.MyToast;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.ShareContent;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.HashMap;
import java.util.Map;

import static com.sczmgk.hotline_pzh.ui.MainActivity.REQUEST_CODE_LOGIN;

/**
 * Created by Administrator on 2016/12/6 0006.
 */
public class NewsDetailActivity extends WebViewBaseActivity {

    private static final int MESSAGE_COLLECTION = 0;

    private int isclloct;
    private int currentIscollect;
    /*显示资讯的webView*/
    private InformationBean informationBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHeader();

        initView() ;

        setListener();
    }

    /**
     * 设置头
     */
    private void setHeader() {

        Intent intent = getIntent();
        //获取url和头部标题以及flags
        informationBean = (InformationBean) intent.getSerializableExtra(Constants.NEWS_DETAIL_ITEM);
        isclloct = informationBean.isclloct;
        currentIscollect = isclloct;
        IndicatorInfos byQuery = InformationTitleDaoImpl.getIntance(NewsDetailActivity.this).findByQuery(informationBean.modeltype);

        String title = null ;
        if (byQuery != null) {
            title = byQuery.title;
        }

        if (!Tools.isEmpty(title)) {
            setTitle(title);
        }
        setLeftBtnVisibility(View.VISIBLE);
        setShareBtnVisiable(View.VISIBLE);
        setNextRightBtnVisibility(View.VISIBLE);
        setShareBtnBGResource(R.drawable.share);

        //设置星星的显示
        if (informationBean.isclloct == 0) {
            setNextRightBtnBackground(R.drawable.collection);
        } else if (informationBean.isclloct == 1) {
            setNextRightBtnBackground(R.drawable.collection_press);
        }
    }

    @Override
    protected String getUrl() {
        return informationBean.url;
    }

    @Override
    protected void onWebViewPageStarted() {
        // 展示加载的dialog
        loadingDialog = DialogFactory.getLoadingDialog(NewsDetailActivity.this);
        DialogFactory.showDialog(loadingDialog);
    }

    @Override
    protected void onWebViewPageFinished() {
        //当页面加载完成时关闭dialog
        DialogFactory.dismissLoadingDialog(loadingDialog);
    }

    @Override
    protected void onWebViewReceivedError() {
        //当页面加载失败时关闭dialog并弹吐司
        DialogFactory.dismissLoadingDialog(loadingDialog);
        MyToast.show(NewsDetailActivity.this, "网络有问题,请检查网络");
    }

    /**
     * 设置监听
     */
    private void setListener() {

        //右侧分享按钮点击事件
        setShareBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                MyToast.show(NewsDetailActivity.this, "分享被点击了");
//                new ShareAction(NewsDetailActivity.this).withTargetUrl("http://www.joygov.com/").setDisplayList(SHARE_MEDIA.SINA.QQ,SHARE_MEDIA.SINA,SHARE_MEDIA.WEIXIN).setCallback(umShareListener).open();
//                MyToast.showDebug(NewsDetailActivity.this, "分享被点击了");

                ShareAction shareAction = new ShareAction(NewsDetailActivity.this);
                shareAction.setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE);//设置分享平台 三个平台 SHARE_MEDIA.SINA 删除分享
//                shareAction.setDisplayList(SHARE_MEDIA.WEIXIN);//设置分享平台 暂时开放微信
                shareAction.setCallback(umShareListener);//设置监听
                ShareContent shareContent = new ShareContent();
                shareContent.mTitle = "这是一个标题";
                shareContent.mTargetUrl = "http://www.joygov.com/";
                shareContent.mText = "这是一个文本";
                shareContent.mTitle = informationBean.origin;
                shareContent.mTargetUrl = informationBean.url;
                shareContent.mText = informationBean.title;
                shareAction.setShareContent(shareContent);
                shareAction.open();
            }
        });

        //右侧收藏按钮点击事件
        setNextRightBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //判断是否登录
                if (!CacheUtils.getBooleanData(NewsDetailActivity.this, Constants.IS_LOGIN_KEY, false)) {
                    DialogFactory.chooseDialog(NewsDetailActivity.this, getResources().getString(R.string.dialog_login_show),
                            getResources().getString(R.string.sure), getResources().getString(R.string.cancel), new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(NewsDetailActivity.this, LoginActivity.class);
                                    startActivityForResult(intent, REQUEST_CODE_LOGIN);
                                }
                            }, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                }
                            }).show();

                    return;
                }

                // 展示加载的dialog
                loadingDialog = DialogFactory.getLoadingDialog(NewsDetailActivity.this);
                DialogFactory.showDialog(loadingDialog);
                if (informationBean.isclloct == 1) {
                    unCollection();
                } else {
                    collection();
                }


            }
        });

        //左侧返回按钮
        setLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                if (flags != Constants.MY_COLLECTION_FLAG_INFO) {
//                    //跳转到资讯主页
//                    UIUtils.startActivity(NewsDetailActivity.this, NewsHomeActivity.class);
//                }
                mFinish();
            }
        });
    }

    /**
     * 显示收藏的Toast
     */
    private void showCollectionToast() {

        Toast toast = new Toast(NewsDetailActivity.this);

        //设置窗体的的内容
        ImageView imageView = new ImageView(NewsDetailActivity.this);
        imageView.setImageResource(R.drawable.already_collected);

        toast.setView(imageView);
        toast.setGravity(Gravity.CENTER, 0, 0);

        toast.show();

    }

    private void collection() {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("userid", CacheUtils.getIntData(NewsDetailActivity.this, Constants.LOGIN_UID, 0));
        maps.put("newsid", informationBean.id);
        MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_COLLECTION, maps, MyHttp.POST, NewsDetailActivity.this, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {
                DialogFactory.dismissLoadingDialog(loadingDialog);
                mHandler.sendEmptyMessage(MESSAGE_COLLECTION);
                currentIscollect = 1;
            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }

            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                super.onErrorCodeError(mError);
                DialogFactory.dismissLoadingDialog(loadingDialog);
                DialogFactory.warningDialog(NewsDetailActivity.this, mError.msg);
            }
        });
    }

    private void unCollection() {
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("userid", CacheUtils.getIntData(NewsDetailActivity.this, Constants.LOGIN_UID, 0));
        maps.put("newsid", informationBean.id);
        MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_DELECT_COLLECTION, maps, MyHttp.POST, NewsDetailActivity.this, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {
                DialogFactory.dismissLoadingDialog(loadingDialog);
                mHandler.sendEmptyMessage(MESSAGE_COLLECTION);
                currentIscollect = 0;
            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }

            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                super.onErrorCodeError(mError);
                DialogFactory.dismissLoadingDialog(loadingDialog);
                DialogFactory.warningDialog(NewsDetailActivity.this, mError.msg);
            }
        });
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MESSAGE_COLLECTION:
                //设置星星的显示
                if (informationBean.isclloct == 0) {
                    informationBean.isclloct = 1;
                    setNextRightBtnBackground(R.drawable.collection_press);
                    showCollectionToast();
                } else if (informationBean.isclloct == 1) {
                    informationBean.isclloct = 0;
                    setNextRightBtnBackground(R.drawable.collection);
                }

                break;
        }
    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (flags != Constants.MY_COLLECTION_FLAG_INFO) {
//                //跳转到资讯主页
//                UIUtils.startActivity(NewsDetailActivity.this, NewsHomeActivity.class);
//            }

            mFinish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void mFinish(){
        if(isclloct != currentIscollect){
            MainHomeDataObserver.getInstance().hasNewMes(true);
            setResult(RESULT_OK);
        }
        finish();
    }
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            MyLog.d("plat", "platform" + platform);

//            Toast.makeText(NewsDetailActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(NewsDetailActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
//                MyLog.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
//            Toast.makeText(NewsDetailActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        MyLog.d(TAG, "分享回调  ------------------->  onActivityResult");
    }
}
